import api from "@/api";
import { isLoggedIn } from "@/api";

// 缓存键常量
const CACHE_KEYS = {
  LIVENESS: "cachedLiveness",
  LIVENESS_TIME: "cachedLivenessTime",
  CHECKIN_STATUS: "cachedCheckinStatus",
  CHECKIN_TIME: "cachedCheckinTime",
};

// 配置常量
const CONFIG = {
  CACHE_DURATION: 30 * 60 * 1000, // 30分钟缓存过期时间
  AUTO_REFRESH_MIN: 10 * 60, // 最小自动刷新时间（秒）- 10分钟
  AUTO_REFRESH_MAX: 20 * 60, // 最大自动刷新时间（秒）- 20分钟
};

// 活跃度工具类
class ActivityUtils {
  constructor() {
    this.listeners = [];
    this.refreshTimer = null;
    this.rewardCheckTimer = null;
    this.refreshCooldown = false;
    this.isRefreshing = false;
    this.livenessLastUpdateTime = 0;
    this.liveness = 0;
    this.previousLiveness = 0; // 记录上一次的活跃度值
    this.hasCheckedIn = false;
    this.initialized = false;
  }

  // 添加活跃度变化监听器
  addListener(callback) {
    this.listeners.push(callback);
    return () => {
      this.listeners = this.listeners.filter((cb) => cb !== callback);
    };
  }

  // 通知所有监听器活跃度变化
  notifyListeners() {
    const data = this.getActivityData();

    this.listeners.forEach((callback) => {
      try {
        callback(data);
      } catch (error) {
        console.error("活跃度通知监听器出错:", error);
      }
    });
  }

  // 从缓存读取数据
  _getFromCache(key, defaultValue = null) {
    try {
      const value = uni.getStorageSync(key);
      return value !== "" ? value : defaultValue;
    } catch (error) {
      console.error(`读取缓存[${key}]失败:`, error);
      return defaultValue;
    }
  }

  // 写入数据到缓存
  _setToCache(key, value) {
    try {
      uni.setStorageSync(key, value);
      return true;
    } catch (error) {
      console.error(`写入缓存[${key}]失败:`, error);
      return false;
    }
  }

  // 获取活跃度
  async getLiveness() {
    if (!isLoggedIn()) return this.liveness;

    try {
      // 避免多次并发请求
      if (this.isRefreshing) {
        return this.liveness;
      }

      // 先检查缓存中的活跃度数据
      const cachedLiveness = this._getFromCache(CACHE_KEYS.LIVENESS);
      const cachedTime = this._getFromCache(CACHE_KEYS.LIVENESS_TIME, 0);
      const currentTime = Date.now();

      // 如果缓存存在且未过期
      if (
        cachedLiveness !== null &&
        cachedTime &&
        currentTime - cachedTime < CONFIG.CACHE_DURATION
      ) {
        this.previousLiveness = this.liveness;
        this.liveness = cachedLiveness;
        this.livenessLastUpdateTime = cachedTime;

        // 设置下次刷新计时器
        this.startRefreshTimer();

        // 通知监听器（只有当值变化时）
        if (this.previousLiveness !== this.liveness) {
          this.notifyListeners();
        }

        return this.liveness;
      }

      // 缓存不存在或已过期，请求新数据
      this.isRefreshing = true;
      this.notifyListeners();

      const res = await api.activity.getLiveness();
      if (res && res.liveness !== undefined) {
        this.previousLiveness = this.liveness;
        this.liveness = res.liveness;

        // 更新缓存
        this._setToCache(CACHE_KEYS.LIVENESS, res.liveness);
        this._setToCache(CACHE_KEYS.LIVENESS_TIME, currentTime);
        this.livenessLastUpdateTime = currentTime;

        // 检查活跃度是否有提升
        // if (this.liveness > this.previousLiveness && this.initialized) {
        //   this._showActivityIncrease(this.liveness - this.previousLiveness);
        // }
      }

      // 设置下次刷新计时器
      this.startRefreshTimer();

      return this.liveness;
    } catch (error) {
      console.error("获取活跃度失败", error);
      return this.liveness;
    } finally {
      this.isRefreshing = false;
      this.notifyListeners();
    }
  }

  // 显示活跃度提升的提示
  // _showActivityIncrease(amount) {
  //   if (amount <= 0) return;

  //   uni.showToast({
  //     title: `活跃度 +${amount}`,
  //     icon: "none",
  //     duration: 2000,
  //   });

  //   // 如果活跃度已满，显示特殊提示
  //   if (this.liveness >= 100) {
  //     setTimeout(() => {
  //       uni.showToast({
  //         title: "恭喜，今日活跃度已满！",
  //         icon: "none",
  //         duration: 3000,
  //       });
  //     }, 2200);
  //   }
  // }

  // 设置下次刷新计时器
  startRefreshTimer() {
    // 清除之前的计时器
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
    }

    // 设置冷却标志
    this.refreshCooldown = true;
    this.notifyListeners();

    // 随机刷新时间 (毫秒)
    const randomTime =
      (Math.floor(
        Math.random() * (CONFIG.AUTO_REFRESH_MAX - CONFIG.AUTO_REFRESH_MIN + 1)
      ) +
        CONFIG.AUTO_REFRESH_MIN) *
      1000;

    // 设置定时器，时间到了自动刷新
    this.refreshTimer = setTimeout(() => {
      this.refreshCooldown = false;
      this.notifyListeners();
      // 自动刷新
      this.refreshLiveness(true);
    }, randomTime);
  }

  // 刷新活跃度
  async refreshLiveness(isAuto = false) {
    if (!isLoggedIn()) return this.liveness;

    // 如果在冷却时间内且不是自动刷新，则显示提示
    if (this.refreshCooldown && !isAuto) {
      return this.liveness;
    }

    // 清除缓存，强制重新获取
    uni.removeStorageSync(CACHE_KEYS.LIVENESS);
    uni.removeStorageSync(CACHE_KEYS.LIVENESS_TIME);

    // 如果不是自动刷新，添加振动反馈
    if (!isAuto) {
      uni.vibrateShort();
    }

    // 获取最新活跃度
    return await this.getLiveness();
  }

  // 检查签到状态
  async checkSignInStatus() {
    if (!isLoggedIn()) return false;

    try {
      // 先检查缓存
      const cachedStatus = this._getFromCache(CACHE_KEYS.CHECKIN_STATUS);
      const cachedTime = this._getFromCache(CACHE_KEYS.CHECKIN_TIME, 0);
      const currentTime = Date.now();

      // 如果缓存存在且未过期
      if (
        cachedStatus !== null &&
        cachedTime &&
        currentTime - cachedTime < CONFIG.CACHE_DURATION
      ) {
        this.hasCheckedIn = cachedStatus;
        this.notifyListeners();
        return this.hasCheckedIn;
      }

      const res = await api.activity.getSignInStatus();
      if (res && res.checkedIn !== undefined) {
        this.hasCheckedIn = res.checkedIn;

        // 更新缓存
        this._setToCache(CACHE_KEYS.CHECKIN_STATUS, res.checkedIn);
        this._setToCache(CACHE_KEYS.CHECKIN_TIME, currentTime);

        this.notifyListeners();
        return this.hasCheckedIn;
      }
      return false;
    } catch (error) {
      console.error("检查签到状态失败", error);
      return false;
    }
  }

  // 清理资源
  cleanup() {
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
      this.refreshTimer = null;
    }

    if (this.rewardCheckTimer) {
      clearInterval(this.rewardCheckTimer);
      this.rewardCheckTimer = null;
    }

    this.listeners = [];
  }

  // 初始化
  async initialize() {
    if (!isLoggedIn()) return;

    try {
      await Promise.all([this.checkSignInStatus(), this.getLiveness()]);
      this.initialized = true;
    } catch (error) {
      console.error("活跃度初始化失败", error);
    }
  }

  // 获取计算后的活跃度相关数据
  getActivityData() {
    // 计算百分比
    const percentage = Math.min(100, this.liveness);

    // 根据活跃度计算颜色
    let progressColor = "#5ecdde"; // 默认浅蓝色

    // 活跃度等级 (1-4)
    let level = 1;
    if (this.liveness < 30) {
      level = 1; // 低
    } else if (this.liveness < 60) {
      level = 2; // 中
    } else if (this.liveness < 100) {
      level = 3; // 高
    } else {
      level = 4; // 满
    }

    return {
      liveness: this.liveness,
      percentage,
      progressColor,
      level,
      hasCheckedIn: this.hasCheckedIn,
      isRefreshing: this.isRefreshing,
      refreshCooldown: this.refreshCooldown,
    };
  }
}

// 创建单例
const activityUtils = new ActivityUtils();

export default activityUtils;
